package cn.com.zpark.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库连接工具
 */
public class DruidUtils {
    private static DataSource dataSource;

    static {
        // 加载配置文件
        InputStream stream = DruidUtils.class.getClassLoader().getResourceAsStream("db.properties");
        Properties p = new Properties();

        try {
            p.load(stream);
            dataSource = DruidDataSourceFactory.createDataSource(p);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取连接
     */
    public static Connection getConn() throws Exception {
        return dataSource.getConnection();
    }

    /**
     * 关闭连接
     */
    public static void close(ResultSet res, Connection conn, Statement... stat){
        if (res != null) {
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        /**************可变参数*************/

        for (Statement statement : stat) {
            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        /**************可变参数*************/


        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
